import java.io.*;
import java.util.*;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class SenseInventory extends DefaultHandler {
  public String senseFile_;
  private TreeMap<String, TreeMap<String, Sense>> wordSense_;

  public SenseInventory(String senseFile) {
    senseFile_ = senseFile;
    wordSense_ = new TreeMap<String, TreeMap<String, Sense>>();
    parseSenseFile();
  }

  private void parseSenseFile() {
    String tmpFile = "tmp.xml";
    try {
      FileWriter writer = new FileWriter(tmpFile);
      FileReader reader = new FileReader(senseFile_);
      XMLReader xmlr = XMLReaderFactory.createXMLReader();
      xmlr.setContentHandler(this);
      xmlr.setErrorHandler(this);

      BufferedReader br = new BufferedReader(reader);
      WSD.formatXMLfile(br, writer);
      reader.close();
      reader = new FileReader(tmpFile);

      // Parse the intermediate XML file.
      xmlr.parse(new InputSource(reader));
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    } catch (SAXParseException spe) {
      StringBuffer sb = new StringBuffer(spe.toString());
      sb.append("\n  Line number: " + spe.getLineNumber());
      sb.append("\nColumn number: " + spe.getColumnNumber());
      sb.append("\n Public ID: " + spe.getPublicId());
      sb.append("\n System ID: " + spe.getSystemId() + "\n");
      System.out.println(sb.toString());
    } catch (SAXException se) {
      System.out.println("loadDOM threw " + se);
      se.printStackTrace(System.out);
    }
  }

  public void insertSense(String word, Sense sense) {
    TreeMap<String, Sense> map = wordSense_.get(word);
    if (map == null) {
      map = new TreeMap<String, Sense>();
    }
    if (map.containsKey(sense.id_)) {
      System.err.println("Something wrong");
    }
    map.put(sense.id_, sense);
    wordSense_.put(word, map);
  }

  String currWord = null;

  public void startElement(String uri, String name, String qName,
      Attributes atts) {
    if (qName.equals("lexelt")) {
      currWord = atts.getValue("item");
    } else if (qName.equals("sense")) {
      String id = atts.getValue("id");
      String source = atts.getValue("source");
      String wn = atts.getValue("wn");
      String synset = atts.getValue("synset");
      String gloss = atts.getValue("gloss");
      Sense sense = new Sense(id, source, wn, synset, gloss);
      insertSense(currWord, sense);
    }
  }

  public Set<String> givePossibleSenses(String word) {
    TreeMap<String, Sense> map = wordSense_.get(word);
    if (map == null) {
      System.err.println("Queried word doesnt exist in dictionary");
      return null;
    }
    return map.keySet();
  }
  
  public TreeMap<String,TreeMap<String,Sense>> getWordSenses() {
    return wordSense_;
  }
}
